# 运行鸿蒙一键构建部署脚本（单模块模式）- Windows PowerShell版本
# 使用前请确保 hdc 已连接设备，DevEco Studio 工具链已安装

# ================== 可配置变量 ==================
# 项目包名(根据实际项目包名修改!!!!!)  
$BUNDLE_NAME = "cn.edu.neusoft.myapplication"
# ================== 可配置变量 ==================

# ================== 固定的变量 ==================
# 临时目录名（使用随机字符串避免冲突）
$TMP_DIR = "hm_deploy_tmp_" + [System.Guid]::NewGuid().ToString("N").Substring(0, 16)
# HAP 包路径
$ENTRY_HAP = "entry\build\default\outputs\default\entry-default-unsigned.hap"

# 检查HAP包是否存在
if (-Not (Test-Path $ENTRY_HAP)) {
    Write-Host "Warning: HAP package not found, trying other paths..." -ForegroundColor Yellow
    # Find latest HAP package
    $latestHap = Get-ChildItem -Path "entry\build" -Recurse -Filter "*.hap" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    if ($latestHap) {
        $ENTRY_HAP = $latestHap.FullName
        Write-Host "Found HAP package: $ENTRY_HAP" -ForegroundColor Green
    } else {
        Write-Host "Error: Cannot find HAP package, please check build output directory" -ForegroundColor Red
    }
# ================== 固定的变量 ==================

# 设置错误时停止执行
$ErrorActionPreference = "Stop"

try {
    Write-Host "1. Installing dependencies..." -ForegroundColor Green
    ohpm install --all --registry https://ohpm.openharmony.cn/ohpm/ --strict_ssl true

    Write-Host "2. Building project..." -ForegroundColor Green
    hvigorw assembleApp

    Write-Host "3. Stopping running application..." -ForegroundColor Green
    try {
        hdc shell aa force-stop "$BUNDLE_NAME"
    } catch {
        Write-Host "Application not running or stop failed, continuing..." -ForegroundColor Yellow
    }

    Write-Host "4. Creating device temporary directory..." -ForegroundColor Green
    Write-Host "  Executing: hdc shell mkdir -p data/local/tmp/$TMP_DIR" -ForegroundColor Gray
    hdc shell mkdir -p "data/local/tmp/$TMP_DIR"

    Write-Host "5. Transferring HAP package to device..." -ForegroundColor Green
    Write-Host "  - Transferring entry.hap..." -ForegroundColor Cyan
    Write-Host "  Executing: hdc file send $ENTRY_HAP data/local/tmp/$TMP_DIR/entry.hap" -ForegroundColor Gray
    hdc file send "$ENTRY_HAP" "data/local/tmp/$TMP_DIR/entry.hap"

    Write-Host "6. Installing application package..." -ForegroundColor Green
    hdc shell bm install -p "data/local/tmp/$TMP_DIR"

    Write-Host "7. Cleaning device temporary files..." -ForegroundColor Green
    hdc shell rm -rf "data/local/tmp/$TMP_DIR"

    Write-Host "8. Starting application..." -ForegroundColor Green
    hdc shell aa start -a EntryAbility -b "$BUNDLE_NAME" -m entry

    Write-Host "Build and deploy completed successfully! Application started." -ForegroundColor Green

} catch {
    Write-Host "Build and deploy failed: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Please check error messages and try again" -ForegroundColor Red
    exit 1
}